package com.jp.completableFuture;

import java.awt.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class CompletableFutureTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {


        //test1();
        //test2();
        test3();

        sleep(1000);

    }
    //同步
    public static void test1() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            sleep(3);
            System.out.println("supplier");
            return "supplier";
        });
        future.thenAccept((a)->{
            sleep(5);
            System.out.println(a);
        });
        System.out.println("========================================");
        System.out.println(future.get());
    }

    public static void test2(){
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            sleep(3);
            System.out.println("supplier");
            return "supplier";
        });
        future.thenAcceptAsync((a)->{
            sleep(5);
            System.out.println(a);
        });;

        try {
            System.out.println("========================================");
            System.out.println(future.get());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    //同步
    public static void test3() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(()->{
            sleep(3);
            return "supplier";
        });
        future.whenComplete((t,v)->{
            sleep(5);
            System.out.println("whenComplete");
        });
        System.out.println("========================================");
        System.out.println(future.get());
    }

    public static void sleep(int t){
        try {
            TimeUnit.SECONDS.sleep(t);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
